package com.gz.tomcat.handler;

import com.gz.servlet_my.GzCalServlet;
import com.gz.servlet_my.GzHttpServlet;
import com.gz.tomcat.GzTomcatV3;
import com.gz.tomcat.http.GzRequest;
import com.gz.tomcat.http.GzResponse;
import com.gz.utils.WebUtils;

import java.io.*;
import java.net.Socket;

public class RequestHandler implements Runnable {
    private Socket socket = null;
    public RequestHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            System.out.println("============tomcat v2版本============");
//            InputStream inputStream = socket.getInputStream();
//            BufferedReader bufferedReader = new BufferedReader(
//                     new InputStreamReader(inputStream));
//            String s="";
//            while((s=bufferedReader.readLine())!=null){
//                //一定要加这句话，否则页面打不开
//                //注意:HTTP 请求是以空行作为请求头和请求体分隔以及整个请求结束的标志。
//                //当客户端发送完请求后，并不会主动关闭输入流，所以 bufferedReader.readLine() 不会返回 null
//                //如果不加这句话会一直在这个while循环出不去，页面打不开
//                //注意与那个mytomcat的区别，那个没有读取请求信息(会有空行)，直接读取的hello.html信息
//                if(s.length()==0){
//                    break;
//                }
//                System.out.println(s);
//            }
            GzRequest gzRequest = new GzRequest(socket.getInputStream());
            GzResponse gzResponse = new GzResponse(socket.getOutputStream());
//            String num1 = gzRequest.getParameter("num1");
//            String num2 = gzRequest.getParameter("num2");
//            System.out.println("请求的参数num1= "+num1);
//            System.out.println("请求的参数num2= "+num2);
//            System.out.println("GzRequest= "+gzRequest);
            String uri = gzRequest.getUri();
//            System.out.println("uri= "+uri);
            if(WebUtils.isHtml(uri)){
                String filename = uri.substring(1);
                OutputStream outputStream=gzResponse.getOutputStream();
                String respHeader = gzResponse.getRespHeader();
                String resmessage=respHeader+WebUtils.readHtml(filename);
                outputStream.write(resmessage.getBytes());
                outputStream.flush();
                outputStream.close();
                return;
            }
            String servletName = GzTomcatV3.servletUrlMapping.get(uri);

            //真正运行方法的是GzHttpServlet的子类(如GzCalServlet)(动态绑定)
//            System.out.println("servletName= "+servletName);
            if(servletName == null) {
                servletName="";
            }
            GzHttpServlet gzHttpServlet = GzTomcatV3.servletMapping.get(servletName);
//            System.out.println("gzHttpServlet= "+gzHttpServlet);
            if(gzHttpServlet != null) {
                //由service()实现doget和dopost方法
                gzHttpServlet.service(gzRequest, gzResponse);
            }else{
                //如果没有这个servlet,返回404提示信息
                String resmessage=gzResponse.getRespHeader()+"<h1>404 Not Found</h1>";
                //相当于response.getWriter
                OutputStream outputStream = gzResponse.getOutputStream();
                outputStream.write(resmessage.getBytes());
                outputStream.flush();
                outputStream.close();
            }
//            OutputStream outputStream = socket.getOutputStream();
            //响应给浏览器
//            GzCalServlet gzCalServlet = new GzCalServlet();
//            gzCalServlet.doGet(gzRequest, gzResponse);
            //用反射得到的类
//            //构建一个http响应头
//            // \r\n表示换行
//            //http响应体需要两个换行 \r\n\r\n
//            String header="HTTP/1.1 200\r\n" +
//                    "Content-Type: text/html;charset=utf-8\r\n\r\n";
//            String response=header+"<h1>你好呀，gz</h1>";
//            System.out.println("=========tomcat v2返回的数据=========");
//            System.out.println(response);
//            outputStream.write(response.getBytes());
//
//            outputStream.flush();
//            outputStream.close();
//            inputStream.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //如果中间报错，那也要确保socket一定关闭
            //否则多个线程都不关闭，会造成阻塞卡死
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
